package org.example.captchademo.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RequestMapping("/admin")
@RestController
public class CaptchaController {
    private static final String ADMIN_KAPTCHA_SESSION_KEY = "ADMIN_KAPTCHA_SESSION_KEY";
    private static final String ADMIN_KAPTCHA_SESSION_DATE = "ADMIN_KAPTCHA_SESSION_DATE";
    private static final Long TIME_OUT = 60 * 1000L;
    @RequestMapping("/check")
    public boolean checkCaptcha(String captcha, HttpSession session) {
        // 验证码是否为空
        if(!StringUtils.hasLength(captcha)) {
            return false;
        }
        // 从 session 中获取验证码和生成验证码的时间
        String key = (String) session.getAttribute(ADMIN_KAPTCHA_SESSION_KEY);
        Date date = (Date) session.getAttribute(ADMIN_KAPTCHA_SESSION_DATE);
        // 验证输入的验证码和生成的验证码是否相等   当前验证码是否超时
        if(key.equals(captcha) && System.currentTimeMillis() - date.getTime() < TIME_OUT) {
            return true;
        }

        return false;
    }
}
